import pymysql
from pymysql.cursors import DictCursor
from utils.log_util import logger


class MysqlDb:
    def __init__(self):
        self.mysql_conf = {
            'host': '10.120.85.210',
            'port': 3306,
            'user': 'zgycompany_database',
            'password': 'zgycompany@135',
            'database': 'zgycompany',
            'charset': 'utf8'
        }
        self.conn = None
        self.cur = None

    def __enter__(self):
        try:
            self.conn = pymysql.connect(**self.mysql_conf)
            self.cur = self.conn.cursor(DictCursor)
            logger.debug(f"数据库连接成功, host: {self.mysql_conf['host']}")
            return self
        except pymysql.Error as e:
            logger.error(f"数据库连接失败: {e}")
            raise

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.cur:
            self.cur.close()
        if self.conn:
            self.conn.close()

    def select_all(self, sql):
        if not self.conn or not self.cur:
            raise RuntimeError("数据库连接未建立")

        try:
            self.cur.execute(sql)
            return self.cur.fetchall()
        except pymysql.Error as e:
            logger.error(f"查询失败: {e} | SQL: {sql[:100]}...")
            return None

    def __str__(self):
        return f"<MysqlDb connection to {self.mysql_conf['host']}>"
